from skimage.io import imread,imsave
from skimage.viewer import ImageViewer
from skimage.measure import structural_similarity
from scipy import ndimage
import numpy#,csv
#import matplotlib.pyplot as plt

def caricaProvino(filename):
	return imread(filename)/255.0

def salvaImmagine(img,filename):
	imsave(filename,img)

def mostraImmagine(image):
	viewer = ImageViewer(image)
	viewer.show()

def cutRGB(rgb,fromY,toY,fromX,toX):
	H = abs(toY-fromY)
	W = abs(toX-fromX)
	rgb_cutted = numpy.zeros((H,W,3))
	for h in range(0,H):
		for w in range(0,W):
			rgb_cutted[h,w,0] = rgb[fromY+h,fromX+w,0]
			rgb_cutted[h,w,1] = rgb[fromY+h,fromX+w,1]
			rgb_cutted[h,w,2] = rgb[fromY+h,fromX+w,2]
	return rgb_cutted

def distanzaRGB(a,b):
	diff = 0.0
	for c in range(0,a.shape[2]):
		diff += structural_similarity(a[:,:,c],b[:,:,c])
	diff /= 3.0
	return round(diff,2)

def estraiTraining(rgbA,rgbB):
	diff = rgbA-rgbB
	height,width = rgbA.shape[0],rgbA.shape[1]
	training = numpy.zeros((height*width,6))
	for y in range(0,height):
		for x in range(0,width):
			if sum(diff[y,x,:]) > 0:
				training[y*x+x] = y,x,rgbA[y,x,0],rgbA[y,x,1],rgbA[y,x,2],0
				rgbA[y,x,0] = 0
				rgbA[y,x,1] = 1
				rgbA[y,x,2] = 0
			#elif sum(abs(diff[y,x,:])) > 0.12:
			else:
				training[y*x+x] = y,x,rgbA[y,x,0],rgbA[y,x,1],rgbA[y,x,2],1
				rgbB[y,x,0] = 0
				rgbB[y,x,1] = 1
				rgbB[y,x,2] = 0
	#salvaImmagine(rgbA, '/home/davide/Dropbox/workspaces/R_RustAnalyzer/RA04/verdeSfondo.jpg')
	#salvaImmagine(rgbB, '/home/davide/Dropbox/workspaces/R_RustAnalyzer/RA04/verdeRuggine.jpg')
	return training

'''
def trainingToCsv(rgb,training):
	c = csv.writer(open("/home/davide/Dropbox/workspaces/R_RustAnalyzer/RA04/training_latest.csv", "wb"))
	c.writerow(["R","G","B","class"])
	for pixel in training:
		r = rgb[pixel[0],pixel[1],0]
		g = rgb[pixel[0],pixel[1],1]
		b = rgb[pixel[0],pixel[1],2]
		c.writerow([r,g,b,pixel[2]]);

def imgToCSV(rgb):
	c = csv.writer(open("/home/davide/Dropbox/workspaces/R_RustAnalyzer/RA04/test_latest.csv", "wb"))
	c.writerow(["y","x","R","G","B"])
	height,width = rgb.shape[0],rgb.shape[1]
	for y in range(0,height):
		for x in range(0,width):
			r = rgb[y,x,0]
			g = rgb[y,x,1]
			b = rgb[y,x,2]
			c.writerow([y,x,r,g,b]);
'''

def imageToDataset(rgb):
	height,width = rgb.shape[0],rgb.shape[1]
	dataset = [];#numpy.zeros((height*width,6))
	for y in range(0,height):
		for x in range(0,width):
			dataset.append([y,x,rgb[y,x,0],rgb[y,x,1],rgb[y,x,2],numpy.NaN])
	return numpy.asarray(dataset)

def datasetToRGB(dataset,img):
	greenized = img.copy()
	for pixel in dataset:
		if pixel[5] == 1:
			greenized[pixel[0],pixel[1],0] = 0
			greenized[pixel[0],pixel[1],1] = 1
			greenized[pixel[0],pixel[1],2] = 0
	return greenized

def datasetToWhiteRust(dataset,img):
	whiteRust = numpy.zeros((img.shape[0],img.shape[1]))
	for pixel in dataset:
		if pixel[5] == 1:
			whiteRust[pixel[0],pixel[1]] = 1
		else:
			whiteRust[pixel[0],pixel[1]] = 0
	return whiteRust

def contaMacchie(img):
	img *= 255

	# smooth the image (to remove small objects); set the threshold
	imgf = ndimage.gaussian_filter(img, 1)
	T = 25 # set threshold by hand to avoid installing `mahotas` or
           # `scipy.stsci.image` dependencies that have threshold() functions
	
	# find connected components
	labeled, nr_objects = ndimage.label(imgf > T)
	#plt.imsave('/home/davide/Dropbox/workspaces/R_RustAnalyzer/RA04/labeled_ruggine.png', labeled)
	return nr_objects	

def contaRuggine(dataset):
	totale = len(dataset)
	ruggine = 0.0
	for classe in dataset:
		if classe == 1:
			ruggine += 1.0
	return ruggine/totale